<?php

namespace app\controller;

use app\BaseController;
use app\tool\Random;
use PDO;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use Swoole\Coroutine;
use Swoole\Coroutine\WaitGroup;
use Swoole\Runtime;
use think\facade\Cache;
use think\facade\Filesystem;
use think\Request;

class Index extends BaseController
{
	
	protected $length = 5000;

	
	/**
	 * 获取内容
	 * @param string $cache
	 * @param int $page
	 * @return void
	 */
	function getContent(string $cache,int $page)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$ret = Cache::get("$cache-$page");
		if ($ret){
			$count = Cache::get("$cache-count");
			$nums = Cache::get("$cache-sort");
			writeJson(['count' => $count, 'ret' => $ret, 'cache' => "$cache", 'nums' => $nums]);
		}else{
			writeJson(0, '没有数据了');
		}
	}
	
	/**
	 * 全排列
	 * @return void
	 */
	public function doCalculat(int $end)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		if ($end < 7 || $end > 37) {
			writeJson(0, '输入值必须大于等于7,小于等于37');
		}
		
		
		$ret = Cache::get("key-$end-1");
		if ($ret) {
			$count = Cache::get("key-$end-count");
			$nums = Cache::get("key-$end-sort");
			writeJson(['count' => $count, 'ret' => $ret, 'cache' => "key-$end", 'nums' => $nums]);
		} else {
	
			list($ret, $nums) = $this->calculate($end);
			$count = count($ret);
			$chunks = array_chunk($ret, $this->length);

			$list =[];
			foreach ($chunks as $key=>$chunk){
				$page = $key+1;
				Cache::set("key-$end-$page", $chunk);
				$list[] = "key-$end-$page";
			}
			Cache::set("key-$end-count",$count);
			$nums = $this->num_sort($nums);
			Cache::set("key-$end-sort",$nums);
			Cache::set("key-$end-list",$list);

			writeJson(['count' => $count, 'ret' => $chunks[0]??[], 'cache' => "key-$end", 'nums' => $nums]);
		}
	}
	
	
	/**
	 * 计算
	 * @param Request $request
	 * @return void
	 */
	function compute(Request $request): void
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$condition = $request->filter('trim')->post('condition');
		$cache = $request->post('cache');
		
		if (empty($condition)) {
			writeJson(0, '条件必须填写');
		}
		
		$list = Cache::get("$cache-list");
		if (!$list) {
			writeJson(0, '左边数据为空');
		}
		
		
		$ret = [];
		$data = [];
		foreach ($list as $item) {
			$data[] = Cache::get($item);
		}
		
		foreach ($data as $row) {
			foreach ($row as $element) {
				$ret[] = $element;
			}
		}
		
		$hide = [];
		
		$condi = explode("\n", $condition);
		
		foreach ($condi as $v) {
			$condi_arr = explode('=', $v);
			if (count($condi_arr) != 2) {
				writeJson(0, '条件错误：' . $v);
			}
			if ($condi_arr[1] == '0') {
				$condi_lift_arr = explode(' ', $condi_arr[0]);
				foreach ($ret as $key => $row) {
					$row_arr = explode(' ', $row);
					$intersection = array_intersect($condi_lift_arr, $row_arr);
					if ($intersection){
						$hide[] = $row;
						unset($ret[$key]);
					}
				}
			} elseif (str_contains($condi_arr[1], '-')) {
				$condi_lift_arr = explode(' ', $condi_arr[0]);
				$condi_right_arr = explode('-', $condi_arr[1]);
				foreach ($ret as $key => $row) {
					$jiaoji = false;
					$row_arr = explode(' ', $row);
					$intersection = array_intersect($condi_lift_arr, $row_arr);
					$count = count(array_intersect($intersection, $condi_lift_arr));
					if ($count >= $condi_right_arr[0] && $count <= $condi_right_arr[1]) {
						$jiaoji = true;
					}
					if (!$jiaoji) {
						$hide[] = $row;
						unset($ret[$key]); //隐藏
					}
				}
				
			} else {
		
				$condi_lift_arr = explode(' ', $condi_arr[0]);
				if ($condi_arr[1] > count($condi_lift_arr)) {
					writeJson(0, '条件错误：' . $v);
				}
				foreach ($ret as $key => $row) {
					$jiaoji = false;
					$row_arr = explode(' ', $row);
					$intersection = array_intersect($condi_lift_arr, $row_arr);
					$count = count(array_intersect($intersection, $condi_lift_arr));
					if (!empty($intersection) && $count == $condi_arr[1]) {
						$jiaoji = true;
					}
					if (!$jiaoji) {
						$hide[] = $row;
						unset($ret[$key]); //隐藏
					}
				}
			}
		}
		$rows = array_values($ret);
	
		$show_ret = array_chunk($rows, $this->length);
		$hide_ret = array_chunk($hide, $this->length);
		$show_count = count($rows);
		$hide_count = count($hide);
		
		$showdata = [];
		foreach ($rows as $number) {
			$numberArray = explode(" ", $number);
			foreach ($numberArray as $element) {
				$showdata[] = $element;
			}
		}
		
		$hidedata = [];
		foreach ($hide as $number) {
			$numberArray = explode(" ", $number);
			foreach ($numberArray as $element) {
				$hidedata[] = $element;
			}
		}
	
		$show_nums = $this->num_sort($showdata);
		$hide_nums = $this->num_sort($hidedata);
		$show_list =[];
		$hide_list =[];
		foreach ($show_ret as $key=>$chunk){
			$page = $key+1;
			Cache::set("$cache,$condition,show-$page", $chunk);
			$show_list[] = "$cache,$condition,show-$page";
		}

		foreach ($hide_ret as $key=>$chunk){
			$page = $key+1;
			Cache::set("$cache,$condition,hide-$page", $chunk);
			$hide_list[] = "$cache,$condition,hide-$page";
		}
		Cache::set("$cache,$condition,show-sort",$show_nums);
		Cache::set("$cache,$condition,hide-sort",$hide_nums);
		Cache::set("$cache,$condition,show-count",$show_count);
		Cache::set("$cache,$condition,hide-count",$hide_count);
		Cache::set("$cache,$condition,show-list",$show_list);
		Cache::set("$cache,$condition,hide-list",$hide_list);

		writeJson(['count' => $show_count, 'ret' => $show_ret[0]??[], 'nums' => $show_nums, 'cache' => "$cache,$condition,show", 'operate' => 'show']);
		
		
	}
	
	/**
	 * 反差
	 * @param string $cache
	 * @param string $operate
	 * @return void
	 */
	function contrast(string $cache, string $operate): void
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		if (!in_array($operate, ['hide', 'show'])) {
			writeJson(0, '操作错误');
		}
		if (str_contains($cache, 'hide') || str_contains($cache, 'show')) {
			$cache = str_replace('hide', '', $cache);
			$cache = str_replace('show', '', $cache);
		}
		$rows = Cache::get("$cache$operate-1");
		if (!$rows) {
			writeJson(0, '没有数据');
		}
		$count = Cache::get("$cache$operate-count");
		$nums = Cache::get("$cache$operate-sort");
		writeJson(['count' => $count, 'cache' => $cache . $operate, 'ret' => $rows, 'nums' => $nums, 'operate' => $operate]);
	}
	
	/**
	 * 导入--
	 * @param Request $request
	 * @return void
	 * @throws Exception
	 */
	function import(Request $request)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$files = $request->file('file');
		$rows = [];
		$str = [];
		if (!$files) {
			writeJson(0, '文件不能为空');
		}
		foreach ($files as $file) {
			
			$filePath = 'storage' . DIRECTORY_SEPARATOR . Filesystem::disk('public')->putFile('/files', $file, 'sha1');
			
			
			if (!is_file($filePath)) {
				writeJson(0, '没有找到文件');
			}
			//实例化reader
			$ext = pathinfo($filePath, PATHINFO_EXTENSION);
			
			if ($ext != 'txt') {
				writeJson(0, '只能导入txt格式');
			}
			
			if (file_exists($filePath)) {
				$content = trim(file_get_contents($filePath));
			} else {
				writeJson(0, '文件不存在');
			}
			
			
			$cellIterator = explode("\r\n", $content);

			foreach ($cellIterator as $value) {
				$str_arr = explode(' ', $value);
				foreach ($str_arr as $va) {
					$str[] = $va;
				}
				$rows[] = $value;
			}
			
		}
		$uuid = Random::uuid();
		$chunks = array_chunk($rows, $this->length);
		$list =[];
		foreach ($chunks as $key=>$chunk){
			$page = $key+1;
			Cache::set("$uuid-$page", $chunk);
			$list[] = "$uuid-$page";
		}
		$count = count($rows);
		Cache::set("$uuid-count",$count);
		$nums = $this->num_sort($str);
		Cache::set("$uuid-sort",$nums);
		Cache::set("$uuid-list",$list);

		writeJson(['count' => $count, 'ret' => $chunks[0]??[], 'nums' => $nums, 'cache' => $uuid]);
		
		
	}
	
	/**
	 * 合集
	 * @param Request $request
	 * @return void
	 */
	function heji(Request $request)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$files = $request->file('file');
		$rows = [];
		$str = [];
		if (!$files) {
			writeJson(0, '文件不能为空');
		}
		$hashTable = array_flip($rows); // 将 $rows 数组转换为哈希表
		foreach ($files as $file) {
			
			$filePath = 'storage' . DIRECTORY_SEPARATOR . Filesystem::disk('public')->putFile('/files', $file, 'sha1');
			
			
			if (!is_file($filePath)) {
				writeJson(0, '没有找到文件');
			}
			//实例化reader
			$ext = pathinfo($filePath, PATHINFO_EXTENSION);
			
			if ($ext != 'txt') {
				writeJson(0, '只能导入txt格式');
			}
			
			if (file_exists($filePath)) {
				$content = trim(file_get_contents($filePath));
			} else {
				writeJson(0, '文件不存在');
			}
			
			$cellIterator = explode("\r\n", $content);
			foreach ($cellIterator as $value) {
				if (!isset($hashTable[$value])) { // 使用 isset 函数来检查值是否存在于哈希表中
					$str_arr = explode(' ', $value);
					foreach ($str_arr as $va) {
						$str[] = $va;
					}
					$rows[] = $value;
					$hashTable[$value] = true; // 更新哈希表
				}
			}
		}
		
		
		$uuid = Random::uuid();
		
		$chunks = array_chunk($rows, $this->length);
		$list =[];
		foreach ($chunks as $key=>$chunk){
			$page = $key+1;
			Cache::set("$uuid-$page", $chunk);
			$list[] = "$uuid-$page";
		}
		$count = count($rows);
		Cache::set("$uuid-count",$count);
		$nums = $this->num_sort($str);
		Cache::set("$uuid-sort",$nums);
		Cache::set("$uuid-list",$list);
		writeJson(['count' => $count, 'ret' => $chunks[0]??[], 'nums' => $nums, 'cache' => $uuid]);
		
	}
	
	/**
	 * 交集
	 */
	function jiaoji(Request $request)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$files = $request->file('file');
		$rows = [];
		$str = [];
		if (!$files) {
			writeJson(0, '文件不能为空');
		}
		foreach ($files as $file) {
			
			$filePath = 'storage' . DIRECTORY_SEPARATOR . Filesystem::disk('public')->putFile('/files', $file, 'sha1');
			
			if (!is_file($filePath)) {
				writeJson(0, '没有找到文件');
			}
			//实例化reader
			$ext = pathinfo($filePath, PATHINFO_EXTENSION);
			
			if ($ext != 'txt') {
				writeJson(0, '只能导入txt格式');
			}
			
			if (file_exists($filePath)) {
				$content = trim(file_get_contents($filePath));
			} else {
				writeJson(0, '文件不存在');
			}
			
			$cellIterator = explode("\r\n", $content);
			foreach ($cellIterator as $value) {
				$rows[] = $value;
			}
		}
	
		$counts = array_count_values($rows);

		$rows = [];
		$count = count($files);
		foreach ($counts as $value => $counta) {
			if ($counta == $count) {
				$arr = explode(' ', $value);
				foreach ($arr as $v) {
					$str[] = $v;
				}
				$rows[] = $value;
			}
		}
		
		$uuid = Random::uuid();
		
		$chunks = array_chunk($rows, $this->length);
		$list =[];
		foreach ($chunks as $key=>$chunk){
			$page = $key+1;
			Cache::set("$uuid-$page", $chunk);
			$list[] = "$uuid-$page";
		}
		$count = count($rows);
		Cache::set("$uuid-count",$count);
		$nums = $this->num_sort($str);
		Cache::set("$uuid-sort",$nums);
		Cache::set("$uuid-list",$list);
		writeJson(['count' => $count, 'ret' => $chunks[0]??[], 'nums' => $nums, 'cache' => $uuid]);
	}
	
	/**
	 * 导出
	 * @return void
	 */
	function export(string $cache)
	{
		ignore_user_abort(true); //连接断开 继续执行.
		set_time_limit(0); // 执行时间无限制
		ini_set("memory_limit","-1");
		$list = Cache::get("$cache-list");
		if (!$list) {
			writeJson(0, '左边数据为空');
		}
		$data = [];
		foreach ($list as $item) {
			$data[] = Cache::get($item);
		}
		$content = "";
		foreach ($data as $row) {
			foreach ($row as $element) {
				$content  .= $element . "\r\n";
			}
		}
		$filename = "export.txt";
		header("Content-type: text/plain");
		header("Content-Disposition: attachment; filename=$filename");
		header("Pragma: no-cache");
		header("Expires: 0");
		echo $content;
	}


	
	function helper($n, $k, $start, &$combination, &$result,&$data)
	{
		if ($k == 0) {
			foreach ($combination as $v){
				$data[] = $v;
			}
			$result[] = implode(' ', $combination);
			return;
		}
		for ($i = $start; $i <= $n; $i++) {
			$combination[] = $i < 10 ? "0$i" : $i;
			$this->helper($n, $k - 1, $i + 1, $combination, $result,$data);
			array_pop($combination);
		}
	}
	
	function calculate($n)
	{
		
		$result = [];
		$combination = [];
		$data = [];
		$this->helper($n, 7, 1, $combination, $result,$data);
		return [$result,$data];
	}
	


	
	
	/**
	 * 频率次数
	 * @param $arr
	 * @return int[]|string[]
	 */
	protected function num_sort($arr)
	{
		// 获取每个值出现的次数
		$counts = array_count_values($arr);
		
		// 将次数和值分别存储到两个数组中
		$countsArray = array_values($counts);
		$counts = array_keys($counts);
		dump($counts);
        exit;
		// 使用 array_multisort() 函数对次数和值同时进行排序
		array_multisort($countsArray, SORT_DESC, $counts, SORT_ASC);
		return $counts;
	}

	
	
}
